<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="阿里云视频点播批量选课"
    width="80%"
    minHeight="600"
    @visible-change="handleVisibleChange"
    :closeFunc="handlerModalClose"
    :showOkBtn="false"
    cancelText="关闭"
  >
    <Row :gutter="16">
      <Col :span="6">
        <BasicTree
          title="工具栏使用"
          toolbar
          search
          ref="asyncTreeRef"
          @select="handlerLoadVideoTable"
          :treeData="treeData"
          :fieldNames="{ key: 'cateId', title: 'cateName', subTotal: 'subTotal' }"
          :load-data="onLoadData"
          :beforeRightClick="getRightMenuList"
        />
      </Col>
      <Col :span="18">
        <BasicTable
          @register="registerAliVideoTable"
          :search-info="videoSearchInfo"
          :title="getVideoTableTitle"
        >
          <template #form-custom> custom-slot </template>
          <template #headerTop>
            <Alert type="info" show-icon>
              <template #message>
                <template v-if="checkedVideoKeys.length > 0">
                  <span>已选中{{ checkedVideoKeys.length }}条记录(可跨页)</span>
                  <a-button type="link" @click="checkedVideoKeys = []" size="small">清空</a-button>
                </template>
                <template v-else>
                  <span>未选中任何项目</span>
                </template>
              </template>
            </Alert>
          </template>
          <template v-if="checkedVideoKeys.length > 0" #toolbar>
            <a-button type="primary" @click="handleAppend2Course">加入课程</a-button>
          </template>
        </BasicTable>
      </Col>
    </Row>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, nextTick, unref, onMounted, reactive, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Row, Col, Alert, message } from 'ant-design-vue';
  import {
    BasicTree,
    TreeActionItem,
    ContextMenuItem,
    TreeActionType,
    TreeItem,
  } from '/@/components/Tree/index';
  import { BasicTable, useTable } from '@/components/Table';
  import {
    getAliVideoListApi,
    getAliVodCategoryListApi,
    getLessonListApi,
    lessonBatchSaveApi,
  } from '@/api/resource/lessonApi';
  import { getAliVideoBasicColumns, getAliVideoFormConfig } from './aliVideoTableData';
  import { isArray } from '/@/utils/is';
  import { uniq } from 'xe-utils';
  import { cloneDeep } from 'lodash-es';
  import { Lesson } from '@/model/resource/lessonModel';

  const emits = defineEmits(['success']);

  const asyncTreeRef = ref<Nullable<TreeActionType>>(null);

  const courseData = ref({});

  const videoSearchInfo = reactive<Recordable>({});

  const treeData = ref<TreeItem[]>([]);

  const [register] = useModalInner((data) => {
    data && onDataReceive(data);
  });

  const checkedVideos = ref<Array<Recordable>>([]);

  const checkedVideoKeys = ref<Array<string | number>>([]);

  const tableHeight = ref({ x: '100%', y: document.body.clientHeight - 630 });

  const getVideoTableTitle = computed(() => {
    return courseData.value.courseName;
  });

  const [registerAliVideoTable, { getForm: getVideoForm, reload }] = useTable({
    api: getAliVideoListApi,
    columns: getAliVideoBasicColumns(),
    useSearchForm: true,
    formConfig: getAliVideoFormConfig(),
    showTableSetting: true,
    tableSetting: { fullScreen: true },
    showIndexColumn: false,
    pagination: false,
    rowKey: 'videoId',
    scroll: tableHeight,
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedVideoKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
    afterFetch: handlerAfterFetch,
    fetchSetting: {
      listField: 'videoList.video',
    },
  });

  function onSelect(record, selected) {
    if (selected) {
      checkedVideos.value = [...checkedVideos.value, record];
      checkedVideoKeys.value = [...checkedVideoKeys.value, record.videoId];
    } else {
      checkedVideoKeys.value = checkedVideoKeys.value.filter(
        (videoId) => videoId !== record.videoId,
      );
      checkedVideos.value = checkedVideos.value.filter((item) => item.videoId !== record.videoId);
    }
  }
  function onSelectAll(selected, selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.videoId);

    if (selected) {
      checkedVideos.value = [...checkedVideos.value, ...changeRows];
      checkedVideoKeys.value = [...checkedVideoKeys.value, ...changeIds];
    } else {
      checkedVideos.value = checkedVideos.value.filter((item) => {
        return !changeIds.includes(item.videoId);
      });
      checkedVideoKeys.value = checkedVideoKeys.value.filter((videoId) => {
        return !changeIds.includes(videoId);
      });
    }
  }

  function onDataReceive(data) {
    courseData.value = data;
  }

  function handleVisibleChange(v) {}

  function getRightMenuList(node: any): ContextMenuItem[] {
    return [
      {
        label: '新增',
        handler: () => {
          console.log('点击了新增', node);
        },
        icon: 'bi:plus',
      },
      {
        label: '删除',
        handler: () => {
          console.log('点击了删除', node);
        },
        icon: 'bx:bxs-folder-open',
      },
    ];
  }

  function onLoadData(treeNode) {
    return new Promise((resolve: (value?: unknown) => void) => {
      if (isArray(treeNode.children) && treeNode.children.length > 0) {
        resolve();
        return;
      }
      if (treeNode.subTotal > 0) {
        const asyncTreeAction: TreeActionType | null = unref(asyncTreeRef);
        if (asyncTreeAction) {
          getAliVodCategoryListApi(treeNode.key).then((response) => {
            asyncTreeAction.updateNodeByKey(treeNode.eventKey, {
              children: response.subCategories.category,
            });
            asyncTreeAction.setExpandedKeys(
              uniq([treeNode.eventKey, ...asyncTreeAction.getExpandedKeys()]),
            );
            resolve();
          });
        }
      } else {
        resolve();
        return;
      }
    });
  }

  async function handleAppend2Course() {
    if (checkedVideoKeys.value.length == 0) {
      message.error('请选择要加入媒体资源');
    }
    const lessonList: Array<Lesson> = checkedVideos.value.map((item) => {
      let lesson: Lesson = {
        title: item.title,
        medialength: parseInt(item.duration * 1000),
        videoPath: item.videoId,
        parentCourseId: courseData.value.courseId,
      };
      return lesson;
    });
    console.log(lessonList);
    await lessonBatchSaveApi(lessonList);
    message.success('成功加入课程');
    reload();
    //props.courseData
  }

  //点击分类节点后，获取媒体资源表格数据
  function handlerLoadVideoTable(selectedKeys, e) {
    console.log(e);
    videoSearchInfo.cateId = selectedKeys[0];
    videoSearchInfo.cateName = e.node.title;
    reload();
  }
  //过滤掉已经入库的video
  async function handlerAfterFetch(tableData) {
    const lessonList = await getLessonListApi({ parentCourseId: courseData.value.courseId });
    const savedVideoIds = lessonList.map((item) => item.videoPath);
    tableData = tableData.filter((item) => {
      return !savedVideoIds.includes(item.videoId);
    });
    return tableData;
  }

  function handlerModalClose() {
    emits('success');
    return true;
  }

  onMounted(() => {
    getAliVodCategoryListApi(0).then((response) => {
      treeData.value = cloneDeep(response.subCategories.category);
    });

    console.log(treeData);
  });
</script>
